package cn.edu.scau.cmi.yangzemin.comprehension.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import cn.edu.scau.cmi.yangzemin.comprehension.domain.Student;
import cn.edu.scau.cmi.yangzemin.comprehension.util.ScauCmiHibernateSessionFactoryUtil;

public class StudentDAO{
	// property constants
	private static final String NAME = "name";
	private static final String ID = "id";     

	private Session session = ScauCmiHibernateSessionFactoryUtil.getSession();

	public void save(Student transientInstance)
	{
		try
		{
			Transaction transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
		}
		catch (RuntimeException re)
		{
			throw re;
		}
	}


	public void delete(Student persistentInstance)
	{
		
		try
		{
			Transaction transaction = session.beginTransaction();
			session.delete(persistentInstance);
			transaction.commit();
			
		}
		catch (RuntimeException re)
		{
			
			throw re;
		}
	}

	public Student findById(Long id)
	{
		return (Student) findByProperty(ID, id).get(0);
	}

	public List findByExample(Student instance)
	{
		
		try  
		{
			List results = session.createCriteria("cn.edu.scau.cmi.yangzemin.comprehension.domain.Student")
					.add(Example.create(instance)).list();
			return results;
		}
		catch (RuntimeException re)
		{
			
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value)
	{
		try
		{
			String queryString = "from Student as model where model." + propertyName + "= ?";
			Query queryObject = session.createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		}
		catch (RuntimeException re)
		{
			
			throw re;
		}
	}

	public Student findByName(Object name)
	{
		return (Student) findByProperty(NAME, name).get(0);
	}

	public List findAll()
	{
	
		try
		{
			String queryString = "from Student";
			Query queryObject = session.createQuery(queryString);
			return queryObject.list();
		}
		catch (RuntimeException re)
		{
		
			throw re;
		}
	}


	public void update(Student instance)
	{
		try
		{
			Transaction transaction = session.beginTransaction();
			session.update(instance);
			transaction.commit();
		}
		catch (RuntimeException re)
		{
		
			throw re;
		} 
	}
}
